﻿using System.IO;
using System.Linq.Expressions;
using System.Threading.Tasks;
using HalalCheck.CustomViews;
using HalalCheck.DataModels;
using HalalCheck.Resources;
using HalalCheck.Utils;
using SpotOffer.Resource;
using Xamarin.Forms;
using XLabs.Forms.Controls;
using XLabs.Ioc;
using XLabs.Platform.Device;
using XLabs.Platform.Services.Media;

namespace HalalCheck.View
{
    public class ChecknSharePage : BasePage
    {
        private Image _stepTwoImage;
        private readonly TaskScheduler _scheduler = TaskScheduler.FromCurrentSynchronizationContext();
        private Label stepTwoImageHalalLabel;

        public ChecknSharePage()
        {
            Title = HalalStrings.CheckShareTitle;
            MakeLayout();
        }

        private void MakeLayout()
        {
            var layout = new RelativeLayout
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,


            };
            var scrollview = new ExtendedScrollView
            {
                Content = layout,
                Padding = AppMargins.ItemPadding,

            };

            var halalchecklogo = new Image
            {
                Source = "centerlogo.png",
                Opacity = 0.30
            };
            layout.Children.Add(halalchecklogo, Constraint.RelativeToParent((p) => (p.Bounds.Width - 200) / 2), Constraint.RelativeToParent((p) => (p.Bounds.Height - 200) / 2), Constraint.RelativeToParent((p => 200)), Constraint.RelativeToParent((p) => 200));

            var stepOneLabel = new Label
            {
                Text = "1. Product name",
                TextColor = AppColors.White
            };
            layout.Children.Add(stepOneLabel, Constraint.Constant(AppMargins.ItemPadding), Constraint.Constant(AppMargins.ItemPadding));

            var stepOneEntry = new ExtendedEntry
            {
                Placeholder = "Type name..",
                BackgroundColor = AppColors.White,
                TextColor = Color.Gray,
                PlaceholderTextColor = Color.Gray,
                Font = Font.SystemFontOfSize(NamedSize.Medium)
            };
            stepOneEntry.SetBinding(ExtendedEntry.TextProperty, "ProductName");
            layout.Children.Add(stepOneEntry,
                Constraint.RelativeToView(stepOneLabel, (p, s) => s.Bounds.Right + AppMargins.ItemPadding),
                Constraint.Constant(AppMargins.ItemPadding), Constraint.RelativeToView(stepOneLabel, (p, s) => p.Bounds.Width - s.Bounds.Right - AppMargins.ItemPadding * 2));

            var stepTwoLabel = new Label
            {
                Text = "2. Product photo",
                TextColor = AppColors.White
            };
            layout.Children.Add(stepTwoLabel, Constraint.Constant(AppMargins.ItemPadding), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding));

            var stepTwoImageLabel = new ExtendedLabel
            {
                BackgroundColor = AppColors.White,
                XAlign = TextAlignment.Center,
                YAlign = TextAlignment.Center,
                TextColor = AppColors.OrigDarkBlue,
                Text = "Take Photo.."
            };
            layout.Children.Add(stepTwoImageLabel, Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Left), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Width), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Width));

            _stepTwoImage = new Image
            {
                BackgroundColor = Color.Transparent,
                Aspect = Aspect.Fill
            };
            layout.Children.Add(_stepTwoImage, Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Left), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Width), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Width));
            _stepTwoImage.GestureRecognizers.Add(new TapGestureRecognizer(OnTap));

            stepTwoImageHalalLabel = new Label();
            stepTwoImageHalalLabel.SetBinding(Label.BackgroundColorProperty, "HalalStatusColor");
            layout.Children.Add(stepTwoImageHalalLabel, Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Left), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding), Constraint.RelativeToView(stepOneEntry, (p, s) => s.Bounds.Width), Constraint.Constant(20));


            var stepTwo = new Label
            {
                Text = "3. Product E-Numbers",
                TextColor = AppColors.White
            };
            layout.Children.Add(stepTwo, Constraint.Constant(AppMargins.ItemPadding), Constraint.RelativeToView(_stepTwoImage, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding));

            var stepThreeEntry = new ExtendedEntry
            {
                BackgroundColor = AppColors.White,
                TextColor = Color.Gray,
                Placeholder = HalalStrings.Search,
                PlaceholderTextColor = Color.Gray,
                Font = Font.SystemFontOfSize(NamedSize.Medium)
            };
            stepThreeEntry.Focused += (s, e) =>
            {
                scrollview.ScrollToAsync(0, stepThreeEntry.Y, true);
            };
            stepThreeEntry.SetBinding(Entry.TextProperty, new Binding("Search"));

            layout.Children.Add(stepThreeEntry,
                Constraint.RelativeToView(stepTwo, (p, s) => s.Bounds.Right + AppMargins.ItemPadding),
                Constraint.RelativeToView(_stepTwoImage, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding), Constraint.RelativeToView(stepTwo, (p, s) => p.Bounds.Width - s.Bounds.Right - AppMargins.ItemPadding * 2));

            var stepThreeListView = new ListView
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                SeparatorVisibility = SeparatorVisibility.None,
                RowHeight = 50 + AppMargins.ItemMargin,

                BackgroundColor = Color.Transparent
            };
            stepThreeListView.SetBinding(ListView.ItemsSourceProperty, new Binding("HalalList"/*,BindingMode.TwoWay*/));
            stepThreeListView.ItemSelected += (sender, e) =>
            {
                if (e.SelectedItem == null)
                    return; // don't do anything if we just de-selected the row
                // ((HalalItem) e.SelectedItem).Checked = true;
                //Navigation.PushAsync(ViewFactory.CreatePage<HalalItemViewModel, HalalItemPage>((v, p) => { v.SelectedHalalItem = (HalalItem)e.SelectedItem; }) as Page, true);
                ((ListView)sender).SelectedItem = null; // de-select the row
            };
            stepThreeListView.ItemTemplate = new DataTemplate(MakeHalalItemLayout);

            layout.Children.Add(stepThreeListView, Constraint.Constant(AppMargins.ItemPadding), Constraint.RelativeToView(stepThreeEntry, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding), Constraint.RelativeToParent((p) => p.Bounds.Width - AppMargins.ItemPadding * 2), Constraint.Constant(150 + AppMargins.ItemMargin * 3));

            var stepFourLabel = new Label
            {
                Text = "4. Share product",
                TextColor = AppColors.White
            };
            layout.Children.Add(stepFourLabel, Constraint.Constant(AppMargins.ItemPadding), Constraint.RelativeToView(stepThreeListView, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding));

            var shareProductButton = new Button
            {
                BackgroundColor = AppColors.White,
                TextColor = AppColors.OrigDarkBlue,
                Text = "Click"
            };
            shareProductButton.SetBinding(Button.CommandProperty, "ShareCommand");
            layout.Children.Add(shareProductButton,
                Constraint.RelativeToView(stepFourLabel, (p, s) =>

                    s.Bounds.Right + AppMargins.ItemMargin

                ), Constraint.RelativeToView(stepThreeListView, (p, s) => s.Bounds.Bottom + AppMargins.ItemPadding));

            Content = scrollview;
        }

        private async void OnTap(Xamarin.Forms.View v, object arg)
        {
            var device = Resolver.Resolve<IDevice>();

            ////RM: hack for working on windows phone? 
            var mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;

            MediaFile mediaFile =
                await
                    mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions
                    {
                        DefaultCamera = CameraDevice.Rear,
                        MaxPixelDimension = 400,
                        PercentQuality = 40
                    }).ContinueWith(t =>
                    {
                        if (t.IsFaulted)
                        {

                        }
                        else if (t.IsCanceled)
                        {

                        }
                        else
                        {
                            mediaFile = t.Result;
                            if (Device.OS == TargetPlatform.Android)
                            {
                                _stepTwoImage.Source =
                                    ImageSource.FromStream(
                                        () =>
                                            new MemoryStream(
                                                DependencyService.Get<IImageServices>()
                                                    .CompressImage(ReadFully(mediaFile.Source), 40)
                                                    .Result));
                            }
                            else
                            {
                                _stepTwoImage.Source = ImageSource.FromStream(() => mediaFile.Source);
                            }

                            return mediaFile;
                        }
                        return null;
                    }, _scheduler);
        }

        public static byte[] ReadFully(Stream input)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                input.CopyTo(ms);
                return ms.ToArray();
            }
        }


        private ViewCell MakeHalalItemLayout()
        {

            var itemLayout = new RelativeLayout
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand,

            };

            var background = AppViews.WhiteRounded();

            itemLayout.Children.Add(background, Constraint.Constant(0), Constraint.Constant(0), Constraint.RelativeToParent((p) => (p.Bounds.Width)), Constraint.RelativeToParent((p) => (p.Bounds.Height - AppMargins.ItemPadding)));

            var halalColor = AppViews.WhiteRounded();
            halalColor.SetBinding(BackgroundColorProperty, new Binding("HalalColor"));
            itemLayout.Children.Add(halalColor, Constraint.Constant(AppMargins.ItemMargin), Constraint.Constant(AppMargins.ItemMargin), Constraint.Constant(50), Constraint.RelativeToView(background, (parent, s) => s.Bounds.Height - AppMargins.ItemMargin * 2));

            var halalid = new ExtendedLabel
            {
                XAlign = TextAlignment.Start,
                YAlign = TextAlignment.Start,
                FontSize = (Device.GetNamedSize(NamedSize.Small, typeof(Label))),
                FontAttributes = FontAttributes.Bold,
                TextColor = AppColors.OrigDarkBlue,
                LineBreakMode = LineBreakMode.TailTruncation,
            };
            halalid.SetBinding(Label.TextProperty, new Binding("Id"));
            itemLayout.Children.Add(halalid, Constraint.RelativeToView(halalColor, (p, s) => (s.Bounds.Right + AppMargins.ItemPadding)), Constraint.Constant(AppMargins.ItemPadding), Constraint.RelativeToView(halalColor, (p, s) => (p.Bounds.Width - s.Bounds.Width - AppMargins.ItemPadding * 3 - 50)));


            var halaltext = new ExtendedLabel
            {
                XAlign = TextAlignment.Start,
                YAlign = TextAlignment.Start,
                FontSize = (Device.GetNamedSize(NamedSize.Small, typeof(Label))),
                TextColor = AppColors.OrigDarkBlue,
                LineBreakMode = LineBreakMode.TailTruncation,
                //FontName = "Harabara.otf",
            };
            halaltext.SetBinding(Label.TextProperty, new Binding("Name"));
            itemLayout.Children.Add(halaltext, Constraint.RelativeToView(halalColor, (p, s) => (s.Bounds.Right + AppMargins.ItemPadding)), Constraint.RelativeToView(halalid, (p, s) => (s.Bounds.Bottom)), Constraint.RelativeToView(halalColor, (p, s) => (p.Bounds.Width - s.Bounds.Width - AppMargins.ItemPadding * 3 - 50)));

            var checkItem = new CheckBox
            {
                BackgroundColor = AppColors.LightGrey,
                TextColor = AppColors.OrigDarkBlue,
            };

            checkItem.SetBinding(CheckBox.CheckedProperty, "Checked");
            checkItem.CheckedChanged += ((p, s) =>
            {
                stepTwoImageHalalLabel.SetBinding(Label.BackgroundColorProperty, "HalalStatusColor"); 
            });
            
            itemLayout.Children.Add(checkItem, Constraint.RelativeToParent((p) => p.Bounds.Width - 50), Constraint.RelativeToParent((p) => (10)));
            itemLayout.GestureRecognizers.Add(new TapGestureRecognizer((s, e) =>
        {
            if (checkItem.Checked)
            {
                checkItem.Checked = false;
            }
            else
            {
                checkItem.Checked = true;
            }
            stepTwoImageHalalLabel.SetBinding(Label.BackgroundColorProperty, "HalalStatusColor");
        }));



            return new ViewCell
            {
                View = itemLayout
            };
        }

    }
}
